import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../widgets/platform/adaptive_card.dart';
import '../../widgets/platform/adaptive_button.dart';
import '../../../data/services/data_management_service.dart';
import 'package:go_router/go_router.dart';

/// 数据库连接历史页面
/// 显示已保存的数据库连接列表，允许用户管理这些连接
class ConnectionHistoryPage extends ConsumerStatefulWidget {
  const ConnectionHistoryPage({super.key});

  @override
  ConsumerState<ConnectionHistoryPage> createState() =>
      _ConnectionHistoryPageState();
}

class _ConnectionHistoryPageState extends ConsumerState<ConnectionHistoryPage> {
  List<Map<String, dynamic>> _connections = [];
  bool _isLoading = false;
  String? _error;

  @override
  void initState() {
    super.initState();
    _loadConnections();
  }

  /// 加载已保存的连接
  Future<void> _loadConnections() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      _connections = await DataManagementService.getConnections();
      setState(() {
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _error = '加载连接列表失败: ${e.toString()}';
        _isLoading = false;
      });
    }
  }

  /// 使用连接
  void _useConnection(Map<String, dynamic> connection) {
    // 导航到表选择页面
    context.push('/spreadsheet/tables', extra: connection);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const SelectableText('连接历史'),
        backgroundColor: Colors.blue.shade50,
        foregroundColor: Colors.blue.shade700,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: _buildContent(),
    );
  }

  Widget _buildContent() {
    if (_isLoading) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            SelectableText('正在加载连接列表...'),
          ],
        ),
      );
    }

    if (_error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              size: 64,
              color: Colors.red,
            ),
            const SizedBox(height: 16),
            SelectableText(
              _error!,
              style: const TextStyle(color: Colors.red),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _loadConnections,
              child: const SelectableText('重试'),
            ),
          ],
        ),
      );
    }

    return _buildConnectionList();
  }

  Widget _buildConnectionList() {
    return Column(
      children: [
        // 连接列表
        Expanded(
          child: _connections.isEmpty
              ? _buildEmptyState()
              : _buildConnectionListView(),
        ),

        // 底部操作按钮
        _buildBottomActions(),
      ],
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: AdaptiveCard(
        margin: const EdgeInsets.all(32),
        child: Padding(
          padding: const EdgeInsets.all(32),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Icon(
                Icons.link_off,
                size: 64,
                color: Colors.grey,
              ),
              const SizedBox(height: 16),
              const SelectableText(
                '暂无连接记录',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w500,
                ),
              ),
              const SizedBox(height: 8),
              SelectableText(
                '您还没有保存任何数据库连接',
                style: TextStyle(
                  color: Colors.grey.shade600,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 24),
              ElevatedButton(
                onPressed: () => context.push('/spreadsheet/connect'),
                child: const SelectableText('创建连接'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildConnectionListView() {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: _connections.length,
      itemBuilder: (context, index) {
        final connection = _connections[index];
        return Card(
          margin: const EdgeInsets.only(bottom: 12),
          child: ListTile(
            leading: Icon(
              _getDbIcon(connection['type']),
              color: Colors.blue,
            ),
            title: SelectableText(connection['name']),
            subtitle:
                SelectableText('${connection['host']}:${connection['port']}'),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                IconButton(
                  icon: const Icon(Icons.play_arrow),
                  onPressed: () => _useConnection(connection),
                  tooltip: '使用连接',
                ),
                IconButton(
                  icon: const Icon(Icons.delete),
                  onPressed: () => _confirmDeleteConnection(connection['name']),
                  tooltip: '删除连接',
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildBottomActions() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withValues(alpha: 0.2),
            blurRadius: 4,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: Row(
        children: [
          SelectableText('${_connections.length} 个连接'),
          const Spacer(),
          AdaptiveButton(
            onPressed: () => context.push('/spreadsheet/connect'),
            isPrimary: true,
            child: const SelectableText('新建连接'),
          ),
        ],
      ),
    );
  }

  /// 根据数据库类型获取图标
  IconData _getDbIcon(String dbType) {
    switch (dbType) {
      case 'mysql':
        return Icons.storage;
      case 'postgresql':
        return Icons.account_tree;
      case 'sqlserver':
        return Icons.dns;
      case 'sqlite':
        return Icons.sd_card;
      case 'mariadb':
        return Icons.storage;
      default:
        return Icons.link;
    }
  }

  void _confirmDeleteConnection(String connectionName) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('确认删除'),
        content: SelectableText('确定要删除连接 "$connectionName" 吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              _deleteConnection(connectionName);
            },
            child:
                const SelectableText('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }

  /// 删除连接
  Future<void> _deleteConnection(String connectionName) async {
    try {
      await DataManagementService.deleteConnection(connectionName);
      // 重新加载连接列表
      await _loadConnections();

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: SelectableText('连接已删除'),
            backgroundColor: Colors.green,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: SelectableText('删除失败: ${e.toString()}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }
}
